/***************************************
* Jerato Ver 0.1
* Copyright 2008 Beta.Ito
* MIT License
***************************************/
package com.googlecode.jerato.library;

import java.util.*;
//import java.util.logging.*;

import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;

public class SettingsParser extends DefaultHandler {

	protected static final String TAG_SECTION = "section";
	protected static final String TAG_ITEM = "item";
	
	protected static final String KEY_NAME = "name";
	protected static final String KEY_VALUE = "value";
	
//	protected static final Logger LOG = Logger.getLogger(SettingsParser.class.getName());

	protected String _sectionName;
	protected String _itemName;
	protected Map _sectionMap;
	protected Map _itemMap;
	protected StringBuffer _valueBuffer;

	public SettingsParser(){
		_sectionMap = new HashMap();
	}

	public void startDocument() throws SAXException {
	}
	
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

		if (TAG_SECTION.equals(qName)){
			_sectionName = attributes.getValue(KEY_NAME);
			_itemMap = new HashMap();
		}
		else if (TAG_ITEM.equals(qName)){
			_itemName = attributes.getValue(KEY_NAME);
			String value = attributes.getValue(KEY_VALUE); 
			_valueBuffer = new StringBuffer();
			if(value != null){
				_valueBuffer.append(value);
			}
		}
	}
	
	public void characters(char[] ch, int offset, int length) throws SAXException {
		if(_valueBuffer != null){
			String textData = new String(ch, offset, length);
			_valueBuffer.append(textData);
		}
	}
	
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (TAG_SECTION.equals(qName) && _itemMap != null) {
			_sectionMap.put(_sectionName, _itemMap);
			_itemMap = null;
		}
		else if (TAG_ITEM.equals(qName) && _itemMap != null && _valueBuffer != null){
			String itemValue = _valueBuffer.toString();
			_itemMap.put(_itemName, itemValue);
			_valueBuffer = null;
		}
	}
	
	public Map getSectionMap() {
		return _sectionMap; 
	}
}
